<template>
  <div class="mainBox" ref="boxbox">
    <el-backtop target=".mainBox"></el-backtop>
    <div class="headerBox">
      <el-form :model="searchForm"  ref="ruleForm" :inline="true" label-width="130px" class="demo-ruleForm">
        <el-form-item :label="$t('analyzeData.chooseProof')" >
          <el-select v-model="searchForm.region" :popper-append-to-body="false" :placeholder="$t('analyzeData.chooseProof1')" @change="getSuspectName()">
            <el-option v-for="(item,index) in poofList" :key="index" :label="item.proof_name" :value="item.proof_num"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item  :label="$t('analyzeData.fenge')" >
          <el-select v-model="searchForm.dateFW" :popper-append-to-body="false"  :placeholder="$t('analyzeData.fenge')">
            <el-option  :label="$t('analyzeData.banxiaoshi')" value="1800"></el-option>
            <el-option  :label="$t('analyzeData.yixiaoshi')" value="3600"></el-option>
            <el-option  :label="$t('analyzeData.erxiaoshi')" value="7200"></el-option>
            <el-option  :label="$t('analyzeData.sixiaoshi')" value="14400"></el-option>
            <el-option  :label="$t('analyzeData.ershixiaoshi')" value="43200"></el-option>
            <el-option  :label="$t('analyzeData.day')" value="86400"></el-option>
            <el-option  :label="$t('analyzeData.twoday')" value="172800"></el-option>
            <el-option  :label="$t('analyzeData.threeday')" value="604800"></el-option>
            <el-option  :label="$t('analyzeData.shisiday')" value="1209600"></el-option>
            <el-option  :label="$t('analyzeData.sanshitianday')" value="2592000"></el-option>
            <el-option  :label="$t('analyzeData.bannian')" value="15768000"></el-option>
            <el-option  :label="$t('analyzeData.yinian')" value="31536000"></el-option>
          </el-select>
        </el-form-item>

        <!-- 选择开始时间 -->
        <el-date-picker
            :append-to-body="false"
            v-model="searchForm.starttime"
            style="margin-right:15px;"
            value-format="timestamp"
            type="datetime"
            :placeholder="$t('analyzeData.startTime')"
            align="right"
            :picker-options="pickerOptions">
        </el-date-picker>

        <!-- 选择结束时间 -->
        <el-date-picker
            :append-to-body="false"
            v-model="searchForm.endtime"
            style="margin-right:15px;"
            value-format="timestamp"
            type="datetime"
            :placeholder="$t('analyzeData.endTime')"
            align="right"
            :picker-options="pickerOptions">
        </el-date-picker>

        <el-button type="primary" icon="el-icon-refresh-right" @click="startEcharts">{{$t('analyzeData.jiazaidange')}}</el-button>
       <el-button type="primary" icon="el-icon-refresh" @click="loadingAllPoofData">{{$t('analyzeData.jiazaiall')}}</el-button>
      </el-form>
    </div>
    <div class="dateAnalyzeBox1">
    <div ref="dateAnalyze1" style="height: 60vh; width: 100%;"></div>
      <div class="block" style="margin-top:30px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 50, 100, 150, 200]"
          :page-size="pageSize"
          layout="total,  prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    <allSearch ref="tableBoxList"  :timeLimit="timeLimit" :tableDataInfo="tableDataInfo" />
  </div>
</template>
<script>
import * as echarts from "echarts";
import allSearch from "./search.vue";
import { getXData,getPoof,getNodeTableInfo,getAllPoofData } from '@/api/analyze/eventAnalysis'
import { parseTime } from '@/utils/index'
export default {
  name: "eventAnalysis",
  components: {
    allSearch,
  },
  data() {
    return {
      pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
      echartsData:'',
      allPoof:false,
      tableDataInfo:[],
      // showLoading:true,
      loading:'',
      timeLimit:'',
      tableLoading:"",
      size:'150px',
      searchForm:{
        region:'',
        dateFW:'',
        date1:'',
        date2:'',
        starttime:'',
        endtime:''
      },
      poofList:[],
      splitNumber:0,
      suspect_name:'',
      currentPage:1,
      total:0,
      pageSize:50
    };
  },
  created() {
    this.getPoofList()
    this.allPoof=false;
  },
  mounted() {

  },
  methods: {
      handleSizeChange(val) {
        this.pageSize=val;
        if(this.allPoof){
          this.loadingAllPoofData()
        }else{
          this.initXData();
        }
      },
      handleCurrentChange(val) {
        this.currentPage=val;
        if(this.allPoof){
          this.loadingAllPoofData()
        }else{
          this.initXData();
        }
      },
    // 加载所有检材
    loadingAllPoofData(){
      this.allPoof=true
       this.loading = this.$loading({
          lock: true,
          text: '事件分析中，时间较长请耐心等候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      let data={
        interval:Number(this.searchForm.dateFW),
        starttime:Math.round(this.searchForm.starttime / 1000),
        endtime:Math.round(this.searchForm.endtime / 1000)
      }
      getAllPoofData(data).then(res=>{

        Array.prototype.insert = function (index, item) {
        this.splice(index, 0, item);
        };
        let allPoofList=[]
        let tooger=true

        res.data.forEach(element => {
          let item=[]
          item.insert(0,element.time)
          if(tooger){
            tooger=false
            item.insert(1,Math.random() * (77 - 10) + 0)
          }else{
            tooger=true
            item.insert(1,Math.random() * (-10 - (-77)) + (-77))
          }
          item.insert(2,element.cnt);
          item.insert(3,element.max);
          item.insert(4,element.min);
          item.insert(5,element.model);
          item.insert(6,element.proof_name);
          item.insert(7,element.proof_num);
          item.insert(8,element.suspect_name);

          allPoofList.push(item)
        });
        this.total=allPoofList.length - 1;
        this.echartsData=allPoofList.slice((this.currentPage-1)*this.pageSize,this.currentPage*this.pageSize);

        this.initEcharts1();
        this.loading.close();
      })
    },
    getSuspectName(){
      this.poofList.forEach(element=>{
        if(this.searchForm.region==element.proof_num){
          this.suspect_name=element.suspect_name
        }
      })
    },
    initTableLoading(){
       this.tableLoading = this.$loading({
          lock: true,
          text: '正在努力加载行为详情...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
    },
    initLoading(){
       this.loading = this.$loading({
          lock: true,
          text: '事件分析中，时间较长请耐心等候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
    },
    startEcharts(){
      this.allPoof = false;
      this.initLoading()
      this.initXData()
    },
    getPoofList(){
      getPoof({}).then(res=>{
        this.poofList=res.data
        this.searchForm.region=res.data[0].proof_num
        this.searchForm.dateFW='604800'
      }).catch(err=>{
        this.loading.close();
      })
    },
    reset(){
      this.$refs.ruleForm.resetFields();
    },
    initFormateDate(date){
      return parseTime(date)
    },
    initXData(){
      let data={
        interval:Number(this.searchForm.dateFW),
        proof_num:this.searchForm.region,
        starttime:Math.round(this.searchForm.starttime / 1000),
        endtime:Math.round(this.searchForm.endtime / 1000)
      }
      getXData(data).then(res=>{
        if(res.data.length==0){
          this.$message({
            message: '未发现该检材相关的交易数据！',
            type: 'warning'
          });
          this.echartsData=[]
          this.initEcharts1();
          this.loading.close();
          return
        }
        let arr=[]
        let tooger=true
        res.data.forEach(element=>{
          let item=[]
          for (const iterator in element) {
              let i=element[iterator]
              item.push(i)
          }

          if(tooger){
            tooger=false
            item.unshift(Math.random() * (77 - 10) + 0)
            item.unshift(item[5])
          }else{
            tooger=true
            item.unshift(Math.random() * (-10 - (-77)) + (-77))
            item.unshift(item[5])
          }
          arr.push(item)
        })

        this.total=arr.length - 1;
        this.echartsData=arr.slice((this.currentPage-1)*this.pageSize,this.currentPage*this.pageSize);

        this.initEcharts1();
        this.loading.close();

      }).catch(err=>{
        this.loading.close();
      })
    },
    // 固定y轴数值，横轴时间分割
    initEcharts1() {
      var chartDom = this.$refs.dateAnalyze1;
      var myChart = echarts.init(chartDom);
      let _this=this
      // 渲染列表
      myChart.on('click', params => {
        this.initTableLoading()
          /*param参数包含的内容有：
          //param.name：X轴的值
          //param.data：Y轴的值
          //param.value：Y轴的值
          //param.type：点击事件均为click
          //param.seriesName：legend的名称
          //param.seriesIndex：系列序号（series中当前图形是第几个图形第几个） 
          //param.dataIndex：数值序列（X轴上当前点是第几个点）
          //alert(param.seriesName);  //legend的名称
          // alert(param.name);  //X轴的值
          // alert(option.series[param.seriesIndex].barIds[param.dataIndex]);//获取自定义的值
          */
          // 打印当前点击柱状的数据
          // 30 分(分钟)=1800000 毫秒

          // --------- 请求节点table---------
          let data=''
          if(_this.allPoof){
             data={
              model:params.value[5],
              proof_num:params.value[7],
              start:params.value[4],
              end:params.value[3],
              interval:Number(this.searchForm.dateFW)
            }
          }else{
              data={
              model:params.value[5],
              proof_num:this.searchForm.region,
              start:params.value[0],
              end:params.value[3],
              interval:Number(this.searchForm.dateFW)
            }
          }

          let title=''
            switch (params.value[5]) {
                case 'sms':
                    title = "短信";
                    break;
                case 'wechat':
                    title = "微信";
                    break;
                case 'callrecords':
                    title = "通话记录";
                    break;
                case 'qq':
                    title = "QQ";
                    break;
          }
          sessionStorage.setItem('tableClass',title)
          // 查询嫌疑人姓名
                this.poofList.forEach(element=>{
                  if(this.searchForm.region==element.proof_num){
                      this.suspect_name=element.suspect_name
                    }
                })
                if(!_this.allPoof){
                this.timeLimit=`${title} [ ${this.initFormateDate(params.value[0])} - ${this.initFormateDate(params.value[3])} ] 检材编号：${this.searchForm.region} 嫌疑人：${this.suspect_name}`
                }else{
                  this.timeLimit=`${title} [ ${this.initFormateDate(params.value[4])} - ${this.initFormateDate(params.value[3])}] 检材编号:${params.value[7]} 嫌疑人：${params.value[8]}`
                }
          getNodeTableInfo(data).then(Response=>{
            this.tableDataInfo=Response.data
            this.tableLoading.close();
            
            setTimeout(()=>{
              _this.$refs.tableBoxList.initTableData(title)
            },500)
            var div = this.$refs.boxbox

          let numberScrollTop=0
          let timer=setInterval(()=>{
            numberScrollTop+=50
            if(numberScrollTop<div.scrollHeight){
            div.scrollTop+=numberScrollTop
            }else{
              div.scrollTop=div.scrollHeight
              clearInterval(timer)
            }
          },50)
   

          }).catch(err=>{
          this.loading.close();
      })
      })
      var option;
      var img = new Image();
      img.src = require("../../../assets/images/weChatQQ/man.png");

      option = {
        title: {
          text: "事件行为时间分析图",
          left: "center",
          textStyle: {
            fontSize: 30,
            color: "#5470c6",
            textBorderType: "solid",
          },
          subtextStyle: {
            fontSize: 20,
          },
        },
        tooltip: {
          trigger: "item",
          axisPointer: {
          },
          formatter: (value) => {
            let title=''
            switch (value.data[5]) {
                case 'sms':
                    title = "短信";
                    break;
                case 'qq':
                    title = "QQ";
                    break;
                case 'qqlite':
                    title = "QQ";
                    break;
                case 'qqhd':
                    title = "QQ";
                    break;
                case 'wechat':
                    title = "微信";
                    break;
                case 'callrecords':
                    title = "通话记录";
                    break;
            } 
            if(!_this.allPoof){
              return title + " " + "行为频率：" + value.data[2]+' 时间：'+_this.initFormateDate(value.data[0])+ '点击查看详情';
            }else{
              return title + " " + "行为频率：" + value.data[2]+' 时间：'+_this.initFormateDate(value.data[0])+'-'+value.data[6] +'-检材编号：'+ value.data[7] + '-'+'嫌疑人：'+value.data[8]+' (点击查看详情)';
            }
          },
        },
        xAxis: {
          name: "时间",
          type:'time',
          min:this.echartsData[0][0]-Number(this.searchForm.dateFW), // 起始4,909,707
          // min:1619706010,
          offset: 50,
          // splitNumber:this.splitNumber,
          maxInterval: Number(this.searchForm.dateFW),
          minInterval: Number(this.searchForm.dateFW),
          // Interval:Number(this.searchForm.dateFW)*1000,//--------设置x轴间距
          rotate:45,
          // 时间戳
          data:[0,30,60,90,120,150,180,210,240,270,300,330,360,390,410,440,470,500,530],
          axisLine: {
            show: true,
          },// 显示坐标刻度不显示轴
          lineHeight: 56,
          axisTick: {
            show: true,
          },
          splitLine: {  
            show: true,
          },
           axisLabel: {
            // show:false,
             hideOverlap:true,
             fontSize:12,
             rotate:-90,
             margin:-90,
           formatter: function (val) {
             return _this.initFormateDate(val)
           }
        }
        },
        yAxis: {
          show:false,
          name: "动作数量",
          scale: true,
          position: "left",
          axisLabel: {
            color: "#666",
            formatter: (value) => {
            // x轴绝对值
              return Math.abs(value);
            },
          },
          formatter: (value) => {
            // return value.data[5];
          },
        },
        dataZoom: [
          {
            type: "inside", //图表下方的伸缩条
            show: true, //是否显示  
            xAxisIndex: [0],
              // realtime : true, //拖动时，是否实时更新系列的视图
              // start : 0, //伸缩条开始位置（1-100），可以随时更改
              // end : 100, //伸缩条结束位置（1-100），可以随时更改
            minSpan: 50,
          },
        ],
        series: [
          {
            name: "应用",
            type: "effectScatter",
            rippleEffect: {
              brushType: "stroke",
              number: 2,
              period: 3,
              scale: 1.4,
            },
            labelLine: {
              show: true,
            },
            markLine: {
              show: true,
              showAbove: true,
              length2:20,
              smooth:true,
            },
            // (value: Array|number, params: Object) => string
            // 添加图片
            // symbol:(value, params)=>{
            //   return 'path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5C17.6,3.5,6.8,14.4,6.8,27.6c0,13.3,10.8,24.1,24.101,24.1C44.2,51.7,55,40.9,55,27.6C54.9,14.4,44.1,3.5,30.9,3.5z M36.9,35.8c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H36c0.5,0,0.9,0.4,0.9,1V35.8z M27.8,35.8 c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H27c0.5,0,0.9,0.4,0.9,1L27.8,35.8L27.8,35.8z'
            // },
            legendHoverLink: true,
            width:'100px',
            color:'',
            label: {
              type: "inherit",
              normal: {
                show: false,
                formatter: (value) => {
                  return value.data[5];
                },
                position: "inside",
                textStyle: {
                  color: "#33FFCC",
                  width:10,
                  fontSize: 15,
                  fontStyle: "normal",
                  fontWeight: "bolder",
                  borderColor: "#1ffb04",
                  shadowColor: "1ffb04"
                },
                rich: {
                  img1: {
                    backgroundColor: {image: '../../../assets/images/logo.png'}
                  }
                },
                formatter: function (param) {
                  // img1是rich里面的对应的规则名，自定义即可，
                  // {img|}表示那个规则或者说是空间的占位符的意思
                  var res = param.value + '\n {img1|}'
                  return res;
                }
              },
            },
            data:this.echartsData,
            //  [
            //   [1639745963, 77, 2000, "天猫"],
            //   [1629755963, 77, 2000, "sms"],
            //   [1619755963, -77, 2000, "qq音乐"],
            //   [1619745963, -77, 2000, "wechat"],
            //   [1619735963, 77, 2000, "qq"],
            //   [1629725963, -77, 2000, "抖音"],
            //   [1649715963, 77, 2000, "高德地图"],
            // ],
            // echarts label style customize
            symbol: function (data) {
                  if (data[5] == "wechat") {
                    return "image://";
                  } else if (data[5] == "哈啰单车") {
                    return "image://";
                  } else if (data[5] == "高德地图") {
                    return "image://";
                  } else if (data[5] == "支付宝") {
                    return "image://";
                  } else if (data[5] == "银联支付") {
                    return "image://";
                  } else if (data[5] == "网易云音乐") {
                    return "image://";
                  } else if (data[5] == "谷歌") {
                    return "image://";
                  } else if (data[5] == "qq音乐") {
                    return "image://";
                  } else if (data[5] == "淘宝") {
                    return "image://";
                  } else if (data[5] == "抖音") {
                    return "image://";
                  } else if (data[5] == "qq" || data[5] == "tim" || data[5] == "qqhd" || data[5] == "qqlite") {
                    return "image://";
                  } else if (data[5] == "飞猪") {
                    return "image://";
                  } else if (data[5] == "滴滴出行") {
                    return "image://";
                  } else if (data[5] == "UC浏览器") {
                    return "image://";
                  } else if (data[5] == "京东") {
                    return "image://";
                  } else if (data[5] == "safari浏览器") {
                    return "image://";
                  } else if (data[5] == "360浏览器") {
                    return "image://";
                  } else if (data[5] == "天猫") {
                    return "image://";
                  } else if (data[5] =="sms") {
                    return "image://"
                  }else if(data[5]=='callrecords'){
                    return "image://"
                  }else{}
            },
            symbolSize: function (data) {
              // 设置全局变量表单
              return Math.sqrt(1000);
            },
          },
        ],
      };
      // option && myChart.setOption(option);
      option && myChart.setOption(option);
      // window.addEventListener("resize", () => {
      //   myChart.resize(); 
      // });
      window.onresize = () => {
        myChart.resize();
        //如果有多个表变动在下方依次写下去就可以了
      }
    },
  },
};
</script>
<style>

</style>
<style scoped>

.demo-ruleForm{
  height: auto;
  /* display: flex; */
  /* align-items: center; */
  padding-top: 10px;
}
.loadingBox{
  /* position: absolute; */
  /* top: 100px;
  z-index: 10000; */
  top: -1050px;

}
.mainBox {
  padding: 20px 20px 40px 30px;
  overflow-y: auto;
  height: 100vh;
  background: rgb(245, 245, 245);
}
.dateAnalyzeBox1{
  width: 99%;
  min-height: 650px;
  background: rgb(255, 255, 255);
  margin: 0 auto;
  border-radius: 5px;
  padding-top: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 50px;
  padding-bottom: 30px;
}
.headerBox{
  background: #fff;
  height: auto;
  width: 99%;
  margin: 0 auto;
  margin-bottom: 10px;
  border-radius: 4px;
  padding: 5px 10px;
  display: flex;
  /* align-items: center; */
  flex-wrap: wrap;
}

/* 当屏幕宽度大于2560时 */
@media screen and (min-width: 2360px) {
  .mainBox {
  padding: 20px 20px 40px 30px;
  overflow-y: auto;
  height: 100vh;
  background: rgb(245, 245, 245);
}
}
</style>
